<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="计划编号" prop="planNumber">
        <el-input v-model="queryParams.planNumber" placeholder="请输入计划编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="计划名称" prop="planName">
        <el-input v-model="queryParams.planName" placeholder="请输入计划名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <!-- 排查类别 -->
      <el-form-item label="排查类别" prop="inspectionType">
        <el-select v-model="queryParams.inspectionType" placeholder="请选择排查类别">
          <el-option label="日常性隐患排查" value="1" />
          <el-option label="综合性隐患排查" value="2" />
          <el-option label="季节性隐患排查" value="3" />
          <el-option label="专家类隐患排查" value="4" />
          <el-option label="环保类隐患排查" value="5" />
          <el-option label="外部督导检查" value="6" />
        </el-select>
      </el-form-item>
      <el-form-item label="确认状态" prop="confirmStatus">
        <el-select v-model="queryParams.confirmStatus" placeholder="请选择确认状态">
          <el-option label="未确认" value="0" />
          <el-option label="已确认" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="检查负责人" prop="inspectionLeader">
        <el-input v-model="queryParams.inspectionLeader" placeholder="请输入检查负责人" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="检查部门" prop="hazardDep">
        <treeselect v-model="queryParams.hazardDep" :options="enabledDeptOptions" :show-count="true" placeholder="请选择检测部门"  style="width: 210px;" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['scyfFinal:inspectionPlan:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['scyfFinal:inspectionPlan:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['scyfFinal:inspectionPlan:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['scyfFinal:inspectionPlan:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inspectionPlanList" @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划名称" align="center" prop="planName" />
      <el-table-column label="任务编号" align="center" prop="planNumber" />
      <el-table-column label="排查类别" align="center" prop="inspectionType" />
      <el-table-column label="计划频次" align="center" prop="planFrequency" />
      <el-table-column label="计划次数" align="center" prop="planCount" />
      <el-table-column label="负责人" align="center" prop="inspectionLeader" />
      <el-table-column label="检查部门" align="center" prop="deptId" />
      <el-table-column label="计划状态" align="center" prop="confirmStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['scyfFinal:inspectionPlan:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['scyfFinal:inspectionPlan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改隐患排查计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="计划编号" prop="planNumber" style="width: 300px;">
              <el-input v-model="form.planNumber" placeholder="请输入计划编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排查类别" prop="inspectionType" style="width: 300px;">
              <el-select v-model="form.inspectionType" placeholder="请选择排查类别">
                <el-option label="日常性隐患排查" value="1" />
                <el-option label="综合性隐患排查" value="2" />
                <el-option label="季节性隐患排查" value="3" />
                <el-option label="专家类隐患排查" value="4" />
                <el-option label="环保类隐患排查" value="5" />
                <el-option label="外部督导检查" value="6" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 确认状态 -->
            <el-form-item label="确认状态" prop="confirmStatus" style="width: 300px;">
              <el-select v-model="form.confirmStatus" placeholder="请选择确认状态">
                <el-option label="未确认" value="0" />
                <el-option label="已确认" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="计划名称" prop="planName" style="width: 300px;">
              <el-input v-model="form.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="负责人" prop="inspectionLeader" style="width: 300px;">
              <el-input v-model="form.inspectionLeader" placeholder="请输入检查负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检查部门" prop="deptId" style="width: 300px;">
              <el-input v-model="form.deptId" placeholder="请输入检查部门" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">

          </el-col>
          <el-col :span="8">

          </el-col>
          <el-col :span="8">

          </el-col>
        </el-row>


        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="检查开始时间" prop="startDate" label-width="100px" style="width: 100%;">
              <el-date-picker clearable v-model="form.startDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择检查开始时间" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="~" prop="endDate" label-width="100px" style="width: 100%;">
              <el-date-picker clearable v-model="form.endDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择检查结束时间" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="执行小组" prop="executionTeam">
              <el-input v-model="form.executionTeam" placeholder="请输入执行小组" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="计划频次" prop="planFrequency">
              <el-radio-group v-model="form.planFrequency">
                <el-radio label="1">按固定周期</el-radio>
                <el-radio label="2">按班次</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="频次设置">
              <el-row type="flex" align="middle">
                <el-col :span="2">
                  <span>每</span>
                </el-col>
                <el-col :span="4">
                  <el-input v-model="form.count" placeholder="请输入次数" />
                </el-col>
                <el-col :span="6">
                  <el-select v-model="form.unit" placeholder="请选择">
                    <el-option label="天" value="day"></el-option>
                    <el-option label="周" value="week"></el-option>
                    <el-option label="月" value="month"></el-option>
                    <!-- 可根据需要添加更多选项 -->
                  </el-select>
                </el-col>
                <el-col :span="2">
                  <span>/次</span>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="检查内容" prop="inspectionContent">
          <el-input v-model="form.inspectionContent" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="检查标准" prop="inspectionStandard">
          <el-input v-model="form.inspectionStandard" type="textarea" placeholder="请输入内容" />
        </el-form-item>




        <el-tabs v-model="activeTab">
          <el-tab-pane label="检查风险点" name="riskPoint">
            <el-button type="primary" @click="addRiskPoint">新增</el-button>
            <el-button type="danger" @click="deleteRiskPoint" :disabled="selectedRiskPoint.length === 0">删除</el-button>
            <el-table :data="riskPointData" border @selection-change="handleRiskPointSelectionChange">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="riskPointName" label="风险点名称"></el-table-column>
              <el-table-column prop="riskPointNumber" label="风险点编号"></el-table-column>
              <el-table-column prop="riskEvent" label="风险事件"></el-table-column>
              <el-table-column prop="controlMeasures" label="管控措施"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="text" @click="editRiskPoint(scope.row)">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="相关附件" name="attachment">
            <el-upload action="/your-upload-url" :on-success="handleAttachmentSuccess" :file-list="fileList"
              accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.png">
              <el-button type="primary">上传附件</el-button>
            </el-upload>
          </el-tab-pane>
        </el-tabs>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增风险点" :visible.sync="addRiskDialogVisible" width="600px">
      <el-form ref="riskPointForm" :model="newRiskPoint" label-width="100px">
        <el-form-item label="风险点名称" prop="riskPointName"
          :rules="[{ required: true, message: '请输入风险点名称', trigger: 'blur' }]">
          <el-input v-model="newRiskPoint.riskPointName" placeholder="请输入风险点名称" />
        </el-form-item>
        <el-form-item label="风险点编号" prop="riskPointNumber"
          :rules="[{ required: true, message: '请输入风险点编号', trigger: 'blur' }]">
          <el-input v-model="newRiskPoint.riskPointNumber" placeholder="请输入风险点编号" />
        </el-form-item>
        <el-form-item label="风险事件" prop="riskEvent" :rules="[{ required: true, message: '请输入风险事件', trigger: 'blur' }]">
          <el-input v-model="newRiskPoint.riskEvent" placeholder="请输入风险事件" />
        </el-form-item>
        <el-form-item label="管控措施" prop="controlMeasures"
          :rules="[{ required: true, message: '请输入管控措施', trigger: 'blur' }]">
          <el-input v-model="newRiskPoint.controlMeasures" type="textarea" placeholder="请输入管控措施" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRiskDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNewRiskPoint">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInspectionPlan, getInspectionPlan, delInspectionPlan, addInspectionPlan, updateInspectionPlan, optionData } from "@/api/scyfFinal/inspectionPlan";
import {  deptTreeSelect } from "@/api/system/user";
import editTable from '../../tool/gen/editTable.vue';
import "splitpanes/dist/splitpanes.css";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";


export default {
  components: { editTable },
  name: "InspectionPlan",
  components: { Treeselect },
  data() {
    return {
      activeTab: "riskPoint",
      addRiskDialogVisible: false, // 控制新增风险点弹出框显示隐藏
      newRiskPoint: {
        riskPointName: "",
        riskPointNumber: "",
        riskEvent: "",
        controlMeasures: ""
      },
      riskPointData: [], // 风险点表格数据
      selectedRiskPoint: [], // 选中的风险点数据

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 隐患排查计划表格数据
      inspectionPlanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inspectionType: null,
        confirmStatus: null,
        planName: null,
        inspectionLeader: null,
        hazardDep: null,
        startDate: null,
        endDate: null,
        executionTeam: null,
        planFrequency: null,
        inspectionContent: null,
        inspectionStandard: null,
        riskUnitId: null,
        attachmentPath: null,
        planNumber: null,
        planCount: null
      },
      // 表单参数
      form: {
      },
      activeTab: 'riskPoint', // 默认激活的标签页
      riskPointData: [], // 风险点数据
      selectedRiskPoint: [], // 选中的风险点
      fileList: [],// 存储已上传的文件列表

      // 表单校验
      rules: {
        inspectionType: [
          { required: true, message: "排查类别不能为空", trigger: "change" }
        ],
        confirmStatus: [
          { required: true, message: "确认状态不能为空", trigger: "change" }
        ],
        planName: [
          { required: true, message: "计划名称不能为空", trigger: "blur" }
        ],
        inspectionLeader: [
          { required: true, message: "检查负责人不能为空", trigger: "blur" }
        ],
        hazardDep: [
          { required: true, message: "检查部门不能为空", trigger: "blur" }
        ],
        planNumber: [
          { required: true, message: "计划编号不能为空", trigger: "blur" }
        ],
        inspectionStandard: [
          { required: true, message: "检查标准不能为空", trigger: "blur" }
        ],
        inspectionContent: [
          { required: true, message: "检查内容不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDeptTree();

    // 循环所有列，查看是否有select2的列，如果有，调用给定请求赋值
  },
  methods: {
    addRiskPoint() {
      console.log("addRiskPoint");
      this.addRiskDialogVisible = true; // 显示新增风险点弹出框
      // 重置表单（可选，避免残留上次输入内容）
      this.$nextTick(() => {
        this.$refs.riskPointForm.resetFields();
        this.newRiskPoint = {
          riskPointName: "",
          riskPointNumber: "",
          riskEvent: "",
          controlMeasures: ""
        };
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
      });
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false;
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children);
        }
        return true;
      });
    },
    // 提交新增的风险点
    submitNewRiskPoint() {
      this.$refs.riskPointForm.validate(valid => {
        if (valid) {
          // 表单验证通过，这里可以调用接口提交数据
          // 示例：将新风险点数据添加到表格数据中
          this.riskPointData.push({ ...this.newRiskPoint });
          // 关闭弹出框
          this.addRiskDialogVisible = false;
        }
      });
    },
    // 其他原有方法...
    handleRiskPointSelectionChange(val) {
      this.selectedRiskPoint = val;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.hazardDep = data.id;
      this.handleQuery();
    },
    deleteRiskPoint() {
      // 删除选中的风险点逻辑
      this.riskPointData = this.riskPointData.filter(
        item => !this.selectedRiskPoint.some(selected => selected === item)
      );
      this.selectedRiskPoint = [];
    },
    editRiskPoint(row) {
      // 编辑风险点逻辑（可参考新增逻辑，弹出框显示并回显数据）
      console.log("编辑风险点：", row);
    },
    handleAttachmentSuccess(response, file, fileList) {
      // 上传成功后的处理逻辑，比如把返回的文件信息保存到fileList等
      console.log('附件上传成功', response, file, fileList);
      this.fileList = fileList;
    },
    // 删除风险点
    deleteRiskPoint() {
      // 根据selectedRiskPoint删除数据
      console.log('删除风险点', this.selectedRiskPoint);
    },
    // 处理风险点选中事件
    handleRiskPointSelectionChange(val) {
      this.selectedRiskPoint = val;
    },
    // 编辑风险点
    editRiskPoint(row) {
      console.log('编辑风险点', row);
    },
    // 新增附件
    addAttachment() {
      console.log('新增附件');
    },
    // 删除附件
    deleteAttachment() {
      console.log('删除附件', this.selectedAttachment);
    },
    // 处理附件选中事件
    handleAttachmentSelectionChange(val) {
      this.selectedAttachment = val;
    },
    // 下载附件
    downloadAttachment(row) {
      console.log('下载附件', row);
    },
    // 删除单个附件
    deleteSingleAttachment(row) {
      console.log('删除单个附件', row);
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 表单验证通过，提交数据
          console.log('表单数据', this.form);
          // 这里可以添加提交到后端的逻辑
          this.open = false;
        }
      });
    },
    // 取消
    cancel() {
      this.open = false;
      this.$refs.form.resetFields();
    },
    /** 查询隐患排查计划列表 */
    getList() {
      this.loading = true;
      listInspectionPlan(this.queryParams).then(response => {
        this.inspectionPlanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        inspectionType: null,
        confirmStatus: null,
        planName: null,
        inspectionLeader: null,
        deptId: undefined,
        startDate: null,
        endDate: null,
        executionTeam: null,
        planFrequency: null,
        inspectionContent: null,
        inspectionStandard: null,
        riskUnitId: null,
        attachmentPath: null,
        planNumber: null,
        planCount: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.queryParams.deptId = undefined;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加隐患排查计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInspectionPlan(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改隐患排查计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInspectionPlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInspectionPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除隐患排查计划编号为"' + ids + '"的数据项？').then(function () {
        return delInspectionPlan(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('scyfFinal/inspectionPlan/export', {
        ...this.queryParams
      }, `inspectionPlan_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
